package com.emapp.lccode.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.viewModelScope
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItems
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.amap.api.services.core.AMapException
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import com.emapp.lccode.R
import com.emapp.lccode.adapter.GridImageAdapter
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.BaseConfig.MAX_DISTANCE
import com.emapp.lccode.base.BaseFragment1
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusConfig.REFRESH_ADDRESS
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.bean.Gongxu
import com.emapp.lccode.bean.UpFileKt
import com.emapp.lccode.databinding.FragmentProjectProgressAddBinding
import com.emapp.lccode.mode.ProjectDeviceViewModel
import com.emapp.lccode.utils.DividerOrientation
import com.emapp.lccode.utils.GlideEngine
import com.emapp.lccode.utils.ImageFileCompressEngine
import com.emapp.lccode.utils.MeSandboxFileEngine
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.MyExternalPreviewEventListener
import com.emapp.lccode.utils.SettingUtil.isLocationEnabled
import com.emapp.lccode.utils.divider
import com.emapp.lccode.utils.getColorExt
import com.emapp.lccode.utils.grid
import com.emapp.lccode.utils.openCamera
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.showMessage
import com.emapp.lccode.utils.statesList
import com.emapp.lccode.utils.toEntity
import com.hjq.toast.Toaster
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.utils.MediaUtils
import com.mylhyl.circledialog.CircleDialog
import com.umeng.commonsdk.stateless.UMSLEnvelopeBuild
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

class ProjectProgressAddKtFragment :
    BaseFragment1<ProjectDeviceViewModel, FragmentProjectProgressAddBinding>(),
    AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener {

    private var mData: ArrayList<LocalMedia> = arrayListOf()
    private val imageAdapter: GridImageAdapter by lazy { GridImageAdapter(activity, mData) }
    lateinit var launcherResult: ActivityResultLauncher<Intent>

    private var mData2: ArrayList<LocalMedia> = arrayListOf()
    private val imageAdapter2: GridImageAdapter by lazy { GridImageAdapter(activity, mData2) }
    lateinit var launcherResult2: ActivityResultLauncher<Intent>
    private lateinit var locationClient: AMapLocationClient
    private var infor: DeviceKt = DeviceKt()
    val geocoderSearch: GeocodeSearch by lazy { GeocodeSearch(requireActivity()) }
    var progress_id = ""//是否编辑
    var imageResult = arrayListOf<UpFileKt>()//上传图片返回结果
    var imageResult2 = arrayListOf<UpFileKt>()//上传图片返回结果

    companion object {
        fun newInstance(status: String): ProjectProgressAddKtFragment {
            val args = Bundle()
            args.putString("status", status)
            val fragment = ProjectProgressAddKtFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        if (!isLocationEnabled(requireActivity())) {
            showMessage(
                "手机定位服务未打开！",
                "温馨提示",
                "去开启",
                positiveAction = {
                    val settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivity(settingsIntent)
                })
        }
//        infor =
//            requireActivity().intent.getSerializableExtra("infor1") as DeviceKt? ?: DeviceKt()
        val inf = MmkvUtil.getString("infor1", "")
        if (inf.isNotEmpty()) {
            infor = inf.toEntity<DeviceKt>()!!
            //MmkvUtil.putString("infor1","")
        }
        progress_id = requireActivity().intent.getStringExtra("progress_id").toString()
        val name = requireActivity().intent.getStringExtra("device_name").toString()
        val create_time = requireActivity().intent.getStringExtra("create_time").toString()
        val device_id = requireActivity().intent.getStringExtra("device_id").toString()
        mViewBind.tvName.text = name
        mViewBind.tvCreateTime.text = create_time
        infor.build_status = "2"
        infor.id = device_id
        AMapLocationClient.updatePrivacyShow(activity, true, true)
        AMapLocationClient.updatePrivacyAgree(activity, true)
        geocoderSearch.setOnGeocodeSearchListener(this)
        launcherResult = createActivityResultLauncher(1)
        launcherResult2 = createActivityResultLauncher(2)
        initLocation()
        mViewBind.rvList.run {
            grid(4)
            adapter = imageAdapter
            divider {
                orientation = DividerOrientation.HORIZONTAL
                includeVisible = true
                setDivider(10, true)
                setColor(getColorExt(R.color.white))
            }
        }
        imageAdapter.run {
            selectMax = BaseConfig.selectMaxImage
            setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
                override fun onItemClick(v: View?, position: Int) {
                    PictureSelector.create(this@ProjectProgressAddKtFragment)
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setSelectorUIStyle(PictureSelectorStyle())
                        .isPreviewFullScreenMode(true)
                        .setExternalPreviewEventListener(MyExternalPreviewEventListener(this@run))
                        .startActivityPreview(position, true, data)
                }

                override fun openPicture() {
                    // AMapUtils.calculateLineDistance()
                    // 进入相册
                    val content = mViewBind.tvName.text.toString() + "\n  " + infor.lng + "\n" +
                            "  " + infor.lat + "\n"
//                    openCamera(requireContext(), content, data, launcherResult)
                    PictureSelector.create(this@ProjectProgressAddKtFragment)
                        .openGallery(SelectMimeType.ofImage())
                        .setSelectorUIStyle(PictureSelectorStyle())
                        .setImageEngine(GlideEngine.createGlideEngine()) //.setCropEngine(getCropFileEngine())
                        .setCompressEngine(ImageFileCompressEngine())
                        .setSandboxFileEngine(MeSandboxFileEngine())
                        .setSelectionMode(SelectModeConfig.MULTIPLE)
                        //.setAddBitmapWatermarkListener()
                        .isDisplayCamera(true)
                        .setMaxSelectNum(BaseConfig.selectMaxImage)
                        .setSelectedData(data).also {
                            it.forResult(launcherResult)
                        }
                }

            })
        }


        mViewBind.rvList2.run {
            grid(4)
            adapter = imageAdapter2
            divider {
                orientation = DividerOrientation.HORIZONTAL
                includeVisible = true
                setDivider(10, true)
                setColor(getColorExt(R.color.white))
            }
        }
        imageAdapter2.run {
            selectMax = BaseConfig.selectMaxImage
            setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
                override fun onItemClick(v: View?, position: Int) {
                    PictureSelector.create(this@ProjectProgressAddKtFragment)
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setSelectorUIStyle(PictureSelectorStyle())
                        .isPreviewFullScreenMode(true)
                        .setExternalPreviewEventListener(MyExternalPreviewEventListener(this@run))
                        .startActivityPreview(position, true, data)
                }

                override fun openPicture() {
                    // 进入相册
//                    openCamera(requireContext(),data,launcherResult)
                    PictureSelector.create(this@ProjectProgressAddKtFragment)
                        .openGallery(SelectMimeType.ofImage())
                        .setSelectorUIStyle(PictureSelectorStyle())
                        .setImageEngine(GlideEngine.createGlideEngine()) //.setCropEngine(getCropFileEngine())
                        .setCompressEngine(ImageFileCompressEngine())
                        .setSandboxFileEngine(MeSandboxFileEngine())
                        .setSelectionMode(SelectModeConfig.MULTIPLE)
                        //.setAddBitmapWatermarkListener()
                        .isDisplayCamera(true)
                        .setMaxSelectNum(BaseConfig.selectMaxImage)
                        .setSelectedData(data).also {
                            it.forResult(launcherResult2)
                        }
                }

            })
        }
        if (progress_id.isNotBlank() && progress_id != "null") {
            mViewModel.getProgressInfor(progress_id)
        } else {
            mViewModel.getGongxuList(infor.id)
        }
    }

    /**
     * 懒加载
     */
    override fun lazyLoadData() {
    }

    override fun createObserver() {

        mViewModel.run {
            file.observe(viewLifecycleOwner) { resultState ->
                parseState(resultState, {
                    imageResult.add(it)
                    if (mData.isNotEmpty()) upFile()
                    else {
                        if (mData2.isNotEmpty()) upFile2()
                        else {
                            dismissLoading()
                            add()
                        }
                    }
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
            file2.observe(viewLifecycleOwner) { resultState ->
                parseState(resultState, {
                    imageResult2.add(it)
                    if (mData2.isNotEmpty()) upFile2()
                    else {
                        dismissLoading()
                        add()
                    }
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
            deviceAdd.observe(viewLifecycleOwner) { resultState ->
                parseState(resultState, {
                    Toaster.show("提交成功")
                    viewModelScope.launch {
                        EventBus.getDefault()
                            .post(EventBusModel(EventBusConfig.REFRESH_PROJECT_DEVICE))
                        delay(500)
                        activity?.finish()
                    }
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
            device.observe(viewLifecycleOwner) { resultState ->
                parseState(resultState, {
                    if (it.isNotEmpty())
                        setInfo(it[0])
                    mViewModel.getGongxuList(infor.id)
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
            gongxuList.observe(viewLifecycleOwner) { resultState ->
                parseState(resultState, {
                    if (it.isNotEmpty()) {
                        gx.clear()
                        if (progress_id.isNotBlank() && progress_id != "null") {
                            val index = it.indexOfFirst { g -> g.id == infor.well_process_id }
                            if (index != -1) {
                                val g = it[index]
                                gx.add(g)
//                                mViewBind.tvGongxu.text = g.itemLabel
//                                infor.well_process_id = g.id
//                                infor.name =g.itemLabel
//                                if (index < it.size - 1){
//                                    gx.add(it[index + 1])
//                                }
                            }
                        } else {
                            val gs = it.filter { g -> g.status == "1" }
                            gx.addAll(gs)
                            if (gx.isNotEmpty()) {
                                mViewBind.tvGongxu.text = gx[0].itemLabel
                                infor.well_process_id = gx[0].id
                                infor.name = gx[0].itemLabel
                            }
                        }
                    }
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
        }

    }

    var gx = arrayListOf<Gongxu>()
    fun setInfo(info: DeviceKt) {
        infor.id = info.device_id
        infor.progress_id = info.id
        infor.well_process_id = info.well_process_id
        infor.name = info.name
        mViewBind.run {
            tvName.text = info.welllname
            //   tvCreateTime.text = info.create_time
            tvContent.setText(info.content)
            tvGongxu.setText(info.name)
            tvRemark.setText(info.remark)
        }
        if (info.fileArray != null) {
            infor.fileArray = info.fileArray
            var images: ArrayList<LocalMedia> = arrayListOf()
            info.fileArray.forEach {
                val l = LocalMedia()
                l.path = BaseConfig.ROOT_URL + it.filepath
                l.compressPath = BaseConfig.ROOT_URL + it.filepath
                images.add(l)
            }
            imageAdapter.data.clear()
            imageAdapter.data.addAll(images)
            imageAdapter.notifyDataSetChanged()
        }
        if (info.materialsfileArray != null) {
            infor.materialsfileArray = info.materialsfileArray
            var images: ArrayList<LocalMedia> = arrayListOf()
            info.materialsfileArray.forEach {
                val l = LocalMedia()
                l.path = BaseConfig.ROOT_URL + it.filepath
                l.compressPath = BaseConfig.ROOT_URL + it.filepath
                images.add(l)
            }
            imageAdapter2.data.clear()
            imageAdapter2.data.addAll(images)
            imageAdapter2.notifyDataSetChanged()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            REFRESH_ADDRESS -> {}
            else -> {}
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
        destroyLocation()
    }

    @SuppressLint("CheckResult")
    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.tvName,
            mViewBind.tvState,
            mViewBind.tvGongxu,
            mViewBind.btOk
        ) {
            when (it.id) {
                R.id.tv_state -> {
                    MaterialDialog(requireContext()).show {
                        cancelable(true)
                        lifecycleOwner(viewLifecycleOwner)
                        listItems(null, statesList) { v, index, text ->
                            mViewBind.tvState.text = text
                            infor.build_status = if (text == "未开工") "1" else "2"
                        }
                    }
                }

                R.id.tv_gongxu -> {
                    CircleDialog.Builder()
                        .setItems(gx) { _, position ->
                            mViewBind.tvGongxu.text = gx[position].itemLabel
                            infor.well_process_id = gx[position].id
                            infor.name = gx[position].itemLabel
                            true
                        }
                        .setNegative("取消", null)
                        .show(parentFragmentManager)
                }

                R.id.bt_ok -> {//
//                    if (laln == null) {// 距离判断
//                        initLocation()
//                        return@setOnclickNoRepeat
//                    }
//                    val l2 = LatLng(infor.lat!!.toDouble(), infor.lng!!.toDouble())
//                    val distance = AMapUtils.calculateLineDistance(l2, laln).toBigDecimal()
//                    // log_e("distance===="+distance)
//                    if (distance.compareTo(MAX_DISTANCE.toBigDecimal()) == 1) {
//                        Toaster.show("请在工程区域内操作(${distance}米)")
//                        return@setOnclickNoRepeat
//                    }
                    mData.clear()
                    mData.addAll(imageAdapter.data)
                    imageResult.clear()
                    mData2.clear()
                    mData2.addAll(imageAdapter2.data)
                    imageResult2.clear()
                    var content = mViewBind.tvContent.text.toString()

                    val remark = mViewBind.tvRemark.text.toString()
                    infor.remark = remark


                    val year =
                        try {
                            infor.year.toInt()
                        } catch (e: Exception) {
                            0
                        }
                    if (year < 2024 && mViewBind.tvGongxu.text.toString().isBlank()) {
                        if (content.isBlank()) {
                            Toaster.show("请输入上报内容")
                            return@setOnclickNoRepeat
                        } else {
                            infor.name = content
                        }
                    } else {
                        val name = mViewBind.tvGongxu.text.toString()
                        if (name.isBlank()) {
                            Toaster.show("请输入工序")
                            return@setOnclickNoRepeat
                        }
                        infor.name = name
                    }
                    if (content.isBlank()) {
                        content = infor.name
                    }
                    infor.content = content
                    if (mData.isEmpty()) {
                        Toaster.show("请上传现场图片")
                        return@setOnclickNoRepeat
                    }
                    if (mData.isNotEmpty()) {
                        showLoading("正在上传图片")
                        upFile()
                    } else {
                        if (mData2.isNotEmpty()) {
                            showLoading("正在上传图片")
                            upFile2()
                        } else
                            add()

                    }
                }
            }
        }
    }

    private fun add() {
        infor.file_ids = imageResult.joinToString(",") { file -> file.id }
        infor.materials_file_ids = imageResult2.joinToString(",") { file -> file.id }
        mViewModel.addProgress(infor)
    }

    private fun upFile() {
        if (!mData[0].availablePath.isNullOrBlank() && !mData[0].availablePath.startsWith("http")) {
            val file = File(mData[0].availablePath)
            mViewModel.upFileDevice(file)
            mData.removeAt(0)
        } else {
            if (mData[0].availablePath.startsWith("http")) {
                val result =
                    infor.fileArray.find { BaseConfig.ROOT_URL + it.filepath == mData[0].availablePath }
                if (result != null)
                    imageResult.add(UpFileKt(result.id, "", "", "", "", ""))
            }
            mData.removeAt(0)
            if (mData.isNotEmpty()) upFile()
            else {
                if (mData2.isNotEmpty()) upFile2()
                else {
                    dismissLoading()
                    add()
                }
            }

        }
    }

    private fun upFile2() {
        if (!mData2[0].availablePath.isNullOrBlank() && !mData2[0].availablePath.startsWith("http")) {
            val file = File(mData2[0].availablePath)
            mViewModel.upFileDevice2(file)
            mData2.removeAt(0)
        } else {
            if (mData2[0].availablePath.startsWith("http")) {
                val result =
                    infor.materialsfileArray.find { BaseConfig.ROOT_URL + it.filepath == mData2[0].availablePath }
                if (result != null)
                    imageResult2.add(UpFileKt(result.id, "", "", "", "", ""))
            }
            mData2.removeAt(0)
            if (mData2.isNotEmpty()) upFile2()
            else {
                dismissLoading()
                add()
            }

        }
    }

    private fun initLocation() {
        showLoading("定位中")
        locationClient = AMapLocationClient(activity).apply {
            setLocationOption(getDefaultOption())
            setLocationListener(this@ProjectProgressAddKtFragment)
            startLocation()
        }
    }

    private fun getDefaultOption(): AMapLocationClientOption {
        val mOption = AMapLocationClientOption().apply {
            locationMode =
                AMapLocationClientOption.AMapLocationMode.Hight_Accuracy //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
            isOnceLocation = true
            isLocationCacheEnable = true //可选，设置是否使用缓存定位，默认为true
        }
        return mOption
    }


    private fun stopLocation() {
        locationClient.stopLocation()
    }

    private fun destroyLocation() {
        if (::locationClient.isInitialized) {
            locationClient.onDestroy()
        }
    }

    var laln: LatLng? = null
    override fun onLocationChanged(location: AMapLocation?) {
        dismissLoading()
        if (null != location) {
            laln = LatLng(location.latitude, location.longitude)
        } else {
            log_e("定位失败，loc is null")
        }
        stopLocation()
    }

    private fun createActivityResultLauncher(f: Int): ActivityResultLauncher<Intent> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == AppCompatActivity.RESULT_OK) {
                val selectList = PictureSelector.obtainSelectorList(result.data)
                analyticalSelectResults(selectList, f)
            } else if (resultCode == AppCompatActivity.RESULT_CANCELED) {
                Log.i(TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }

    private fun analyticalSelectResults(result: java.util.ArrayList<LocalMedia>, f: Int) {
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo =
                        MediaUtils.getImageSize(UMSLEnvelopeBuild.mContext, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo =
                        MediaUtils.getVideoSize(UMSLEnvelopeBuild.mContext, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
        }
        if (f == 1) {
            val isMaxSize = result.size == imageAdapter.selectMax
            val oldSize: Int = imageAdapter.data.size
            imageAdapter.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
            imageAdapter.data.clear()
            imageAdapter.data.addAll(result)
            imageAdapter.notifyItemRangeInserted(0, result.size)
        } else {
            val isMaxSize = result.size == imageAdapter2.selectMax
            val oldSize: Int = imageAdapter2.data.size
            imageAdapter2.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
            imageAdapter2.data.clear()
            imageAdapter2.data.addAll(result)
            imageAdapter2.notifyItemRangeInserted(0, result.size)
        }
    }

    override fun onRegeocodeSearched(result: RegeocodeResult?, resultCode: Int) {
        dismissLoading()
        if (resultCode == AMapException.CODE_AMAP_SUCCESS && result != null) {
        }
    }

    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
    }
}